// Singleton Holder template
// Author: Li Wei (oldrev@gmail.com)
// License: GPL

module dayudict.util.singletion;


/**
  * SingletonHolder 是一个单体实现。
  */
final class SingletonHolder(T)
{
   	private static T m_instance;

   	private static this()
   	{
        static assert(is(T == class) || is(T == struct) || is(T == union), 
                "SingletonHolder: struct, union and class only");

		static if(is(T == class))
   			m_instance = new T();
	}

    public static T instance()
    {
		static if(is(T == class))
            assert(m_instance !is null);
           
        return m_instance;
    }

    public static T opCall()
    {
        return instance;
    }

	public static T opCast()
	{
		return instance;
	}

    public static T opAssign(T value)
    {
        m_instance = value;
        return value;
    }
}


debug(DD_Unittest){
unittest
{

	class Foo
	{
		public int x;

	}


	alias SingletonHolder!(Foo) S;
    Foo f = S.instance;
    f.x = 2;
	S().x = 2;
	(cast(Foo)S).x = 2;
}
}//debug(DD_Unittest)
